const Koa = require('koa');
const views = require('koa-views')
const path = require('path')
const Router = require('koa-router')

const { connect, initSchemas, initAdmin } = require('./database/init')


/*
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-session')

const app = new Koa()

app.use(views(path.join(__dirname, './views'), {
    // extension: 'ejs',
    map: { html: 'ejs' }
}))

app.use(bodyParser())
app.use(logger())
app.keys = ['abcd123456789']
const CONFIG = {
    key: 'koa:sess',
    maxAge: 86400000,
    overwrite: true,
    httpOnly: false,
    signed: true,
    rolling: false
}

app.use(session(CONFIG, app))

const routers = require('./routers/index')

app.use(routers.routes()).use(routers.allowedMethods())


app.on('error', function(err, ctx) {
    console.log(err);
})

app.listen(3000, () => {
    console.log('the server is start at port 3000')
})
*/

const R = require('ramda')
const MIDDLEWARES = ['common']

// const router = require('./routes')

const useMiddlewares = (app) => {
    R.map(
        R.compose(
            R.forEachObjIndexed(
                initWith => initWith(app)
            ),
            require,
            name => path.resolve(__dirname, `./middlewares/${name}`)
        )
    )(MIDDLEWARES)
}

;
(async() => {

    // 连接数据库
    await connect()

    // 初始化数据模型
    initSchemas()

    // 初始化账号
    await initAdmin()

    const app = new Koa()
    app.use(views(path.join(__dirname, './views'), {
        // extension: 'ejs',
        map: { html: 'ejs' }
    }))
    await useMiddlewares(app)

    const routers = require('./routers/index')
    app.use(routers.routes()).use(routers.allowedMethods())
    app.on('error', function(err, ctx) {
        console.log(err);
    })

    
    app.listen(3000, () => {
        console.log('the server is start at port 3000')
    })

})()